import numpy as np
import os
from collections import Counter
from Modules.ImageProcess import MyCV2 as imp
def cal_basemap(search_results,k=1):
    """
       计算 numpy 数组 search_results 中出现次数最多的前 k 个元素及其比率。

       参数:
       - search_results: numpy 数组:name_x1,y1,x2,y2
       - k: int 类型，返回前 k 个最常见的元素

       返回:
       - top_k: 列表，包含前 k 个最常见的元素以及它们出现的比率
       """
    name = [os.path.basename(x).split('_')[0] for x in search_results]
    # 计算每个元素出现的次数
    element_counts = Counter(name)
    total_elements = len(search_results)

    # 根据出现次数降序排序，并取前 k 个
    top_k = element_counts.most_common(k)

    # 计算比率
    top_k_with_ratios = [(element, count / total_elements) for element, count in top_k]

    return top_k_with_ratios

def extract_coord(filenames):
    '''
    根据文件名提取坐标H49D001012_9720_18360_10319_18959
    Args:
        filenames:

    Returns:

    '''
    left_top = []
    right_lower = []
    for filename in filenames:
        _,x1,y1,x2,y2 = filename.split('_')
        left_top.append([x1,y1])
        right_lower.append([x2,y2])
    return np.array(left_top,dtype=int).reshape(-1,2),np.array(right_lower,dtype=int).reshape(-1,2)
def cut_basemap(search_results,basemap,path):
    '''
    根据检索小块结果裁切basemap
    Args:
        search_results: E:/satLocate/fusai/basemap/crop\H49D001012_9720_3240_10319_3839.jpg
        basemap: [('h50d001001', 0.845),]
        path: 'E:/satLocate/fusai/basemap/tif'

    Returns:base_img(narray)

    '''
    basemap_name = basemap[0][0]
    filenames_coord = np.array([os.path.splitext(os.path.basename(x))[0] for x in search_results])
    filenames = np.array([x.split('_')[0] for x in filenames_coord])
    index = np.where(filenames == basemap_name)[0]
    # index = choose_element(filenames,basemap)
    left_top, right_lower = extract_coord(filenames_coord[index])
    lt = [min(left_top[:,0]),min(left_top[:,1])]
    rl = [max(right_lower[:,0]),max(right_lower[:,1])]
    base_img = imp.cv_imread(os.path.join(path,basemap_name+'.tif'))
    return base_img[lt[1]:rl[1],lt[0]:rl[0]]
if __name__ == '__main__':
    # 示例
    # arr = np.array(['1_', '2_', '2_', '3_', '3_', '3_', '4_', '4_', '4_', '4_'],dtype=object).reshape(,1)
    arr = np.loadtxt('../test_search_result.txt', dtype=object)
    k = 1
    basemap = cal_basemap(arr, k)
    img = cut_basemap(arr, basemap,'E:/satLocate/fusai/basemap/tif')
    imp.im_write('cut.jpg',img)

